from django import template
register = template.Library()

from django.utils.html import format_html

#自定义标签 分页
@register.simple_tag

def showpages(count,request):
    #count 总页数    p 当前页码   显示10页
    # begin 开始页 end 结束页
    #获取页码
    p = int(request.GET.get('p',1))

    begin = p-4
    end = p+5

    # 当前页码 小于5
    if p<5 :
        begin = 1
        end = 10

    # 当前页码 大于 总页数-5
    if p>count-5:
        begin = count-9
        end = count
    # 总页数小于10
    if count < 10:
        begin = 1
        end = count


    # 获取页面搜索条件
    condation = request.GET.dict()
    condation.pop('p',None)
    s_condation = ''
    for key,val in condation.items():
        s_condation += '&'+key+'='+val

    ps = ''
    #首页
    ps += '<li> <a href="?p='+str(1)+s_condation+ '">首页</a></li>'
    #上一页
    if p>1:
        ps += '<li> <a href="?p='+str(p-1)+s_condation+'">«</a></li>'
    for i in range(begin,end+1):
        #如果是当前页
        if i == p:
            ps +='<li class ="am-active"><a href="?p='+str(i)+s_condation+'">'+str(i)+'</a></li >'
        else:
            ps += '<li> <a href="?p='+str(i)+s_condation+'">'+str(i)+'</a></li>'

    #下一页
    if p<count:
        ps += '<li> <a href="?p='+str(p+1)+s_condation+'">»</a></li>'
    # 尾页
    ps += '<li> <a href="?p=' + str(count) + s_condation + '">尾页</a></li>'

    return format_html(ps)

#自定义标签 缩进
@register.simple_tag
def sj(str1):
    n = str1.count(',')-1
    if n ==0:
        res = n*4*'&nbsp;'
    else:
        res = n*6*'&nbsp;'+'↳'

    return format_html(res)


# 自定义标签 ,解决 购物车价格小计
@register.simple_tag
def cartxj(n1,n2):
    res = n1*n2
    # return round(res,2)
    # return "{:.2f}".format(res)
    return '%.2f'%(res)
